package com.wadesss.flyingformationapp


import android.annotation.SuppressLint
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {

    lateinit var pref: SharedPreferences

    @SuppressLint("SetJavaScriptEnabled", "SdCardPath")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val webapp = findViewById<WebView>(R.id.web_view)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webapp.settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
        }

        pref = getSharedPreferences("Configure", 0)
        val token = pref.getString("token", "").toString()

        webapp.webChromeClient = WebChromeClient()
        webapp.settings.javaScriptCanOpenWindowsAutomatically = true
        webapp.settings.domStorageEnabled = true
        webapp.settings.loadsImagesAutomatically = true
        webapp.settings.javaScriptEnabled = true
        webapp.settings.allowContentAccess = true
        webapp.settings.allowFileAccess = true
        webapp.settings.blockNetworkImage = false
        webapp.settings.databaseEnabled = true

        if (Build.VERSION.SDK_INT > 17) {
            webapp.settings.mediaPlaybackRequiresUserGesture = false
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            webapp.settings.databasePath = "/data/data/" + webapp.context.packageName + "/databases/";
        }

        val js = "window.localStorage.setItem('radar:admin:sessionid', '$token');"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            webapp.settings.safeBrowsingEnabled = false;
            webapp.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        webapp.webViewClient = object : WebViewClient() {
            override fun onPageFinished(webview: WebView, url: String) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    webview.evaluateJavascript(js, null)
                } else {
                    webview.loadUrl("javascript:(function(){" + js.toString() + "})()")
                }
            }
        }

        webapp.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
        webapp.loadUrl("http://122.9.106.181:915")
    }
}